<template>
  <div class="news-detail-page">
    <!-- 页面头部 -->
    <div class="page-header bg-white dark:bg-gray-800 shadow-sm">
      <div class="container mx-auto px-4 py-6">
        <div class="flex flex-col space-y-4">
          <!-- 面包屑导航 -->
          <el-breadcrumb separator="/" class="text-sm">
            <el-breadcrumb-item :to="{ path: '/news' }"
              >新闻资讯</el-breadcrumb-item
            >
            <el-breadcrumb-item>{{ newsDetail.title }}</el-breadcrumb-item>
          </el-breadcrumb>

          <!-- 标题和操作按钮 -->
          <div class="flex items-center justify-between">
            <h1
              class="text-2xl font-bold text-gray-900 dark:text-white line-clamp-1 flex-1 mr-4"
            >
              {{ newsDetail.title }}
            </h1>
            <div class="flex items-center gap-3">
              <el-button-group>
                <el-button
                  type="primary"
                  plain
                  :icon="Share"
                  @click="handleShare"
                  >分享</el-button
                >
                <el-button
                  :type="newsDetail.isFavorited ? 'primary' : 'default'"
                  plain
                  :icon="Star"
                  @click="handleFavorite"
                >
                  {{ newsDetail.isFavorited ? "已收藏" : "收藏" }}
                </el-button>
              </el-button-group>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="flex flex-col lg:flex-row gap-8">
        <!-- 左侧主要内容区 -->
        <div class="flex-1">
          <!-- 新闻内容 -->
          <div
            class="news-content bg-white dark:bg-gray-800 rounded-lg shadow-sm"
          >
            <!-- 新闻元信息 -->
            <div class="border-b border-gray-100 dark:border-gray-700 p-6">
              <div
                class="flex items-center gap-6 text-sm text-gray-500 dark:text-gray-400"
              >
                <div class="author flex items-center">
                  <el-avatar
                    :size="32"
                    :src="newsDetail.author?.avatar"
                    class="mr-2"
                  />
                  <div class="flex flex-col">
                    <span class="font-medium text-gray-900 dark:text-white">{{
                      newsDetail.author?.name
                    }}</span>
                    <span class="text-xs">{{
                      newsDetail.author?.title || "文旅作者"
                    }}</span>
                  </div>
                </div>
                <div class="publish-time flex items-center">
                  <el-icon class="mr-1"><Calendar /></el-icon>
                  <span>{{ formatDate(newsDetail.date) }}</span>
                </div>
                <div class="category">
                  <el-tag
                    size="small"
                    :type="getCategoryType(newsDetail.category)"
                    effect="light"
                  >
                    {{ newsDetail.category }}
                  </el-tag>
                </div>
                <div class="views flex items-center">
                  <el-icon class="mr-1"><View /></el-icon>
                  <span>{{ formatNumber(newsDetail.views) }}次浏览</span>
                </div>
              </div>
            </div>

            <!-- 新闻封面图 -->
            <div class="p-6">
              <div class="relative rounded-lg overflow-hidden">
                <el-image
                  :src="newsDetail.image"
                  class="w-full rounded-lg"
                  fit="cover"
                  :preview-src-list="[newsDetail.image]"
                >
                  <template #placeholder>
                    <div
                      class="image-placeholder flex items-center justify-center h-64 bg-gray-100 dark:bg-gray-700"
                    >
                      <el-icon class="text-4xl text-gray-400"
                        ><Picture
                      /></el-icon>
                    </div>
                  </template>
                </el-image>
                <div
                  class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/60 to-transparent p-4"
                >
                  <p class="text-white text-sm">
                    {{ newsDetail.imageDesc || "新闻图片" }}
                  </p>
                </div>
              </div>
            </div>

            <!-- 新闻正文 -->
            <div class="news-body prose dark:prose-invert max-w-none p-6">
              <div v-html="newsDetail.content" class="leading-relaxed"></div>
            </div>

            <!-- 标签 -->
            <div class="news-tags px-6 pb-6">
              <div class="text-sm text-gray-500 dark:text-gray-400 mb-2">
                相关标签：
              </div>
              <div class="flex flex-wrap gap-2">
                <el-tag
                  v-for="tag in newsDetail.tags"
                  :key="tag"
                  class="cursor-pointer hover:scale-105 transition-transform"
                  effect="plain"
                  @click="handleTagClick(tag)"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </div>

            <!-- 点赞分享工具栏 -->
            <div
              class="action-bar border-t border-gray-100 dark:border-gray-700 p-4"
            >
              <div class="flex items-center justify-center gap-8">
                <div
                  class="action-item flex flex-col items-center cursor-pointer"
                  @click="handleLike"
                >
                  <el-button
                    :type="newsDetail.isLiked ? 'primary' : 'default'"
                    circle
                    :icon="ThumbsUp"
                    class="hover:scale-110 transition-transform"
                  />
                  <span class="text-sm mt-2">
                    {{ formatNumber(newsDetail.likes || 0) }}
                  </span>
                </div>
                <div
                  class="action-item flex flex-col items-center cursor-pointer"
                  @click="handleFavorite"
                >
                  <el-button
                    :type="newsDetail.isFavorited ? 'primary' : 'default'"
                    circle
                    :icon="Star"
                    class="hover:scale-110 transition-transform"
                  />
                  <span class="text-sm mt-2">
                    {{ formatNumber(newsDetail.favorites || 0) }}
                  </span>
                </div>
                <div
                  class="action-item flex flex-col items-center cursor-pointer"
                  @click="handleShare"
                >
                  <el-button
                    circle
                    :icon="Share"
                    class="hover:scale-110 transition-transform"
                  />
                  <span class="text-sm mt-2">分享</span>
                </div>
              </div>
            </div>

            <!-- 评论区 -->
            <div
              class="comments-section border-t border-gray-100 dark:border-gray-700 p-6"
            >
              <h2
                class="text-xl font-bold text-gray-900 dark:text-white mb-6 flex items-center"
              >
                <el-icon class="mr-2"><ChatDotRound /></el-icon>
                评论
                <span
                  class="text-gray-500 dark:text-gray-400 text-base font-normal ml-2"
                >
                  ({{ newsDetail.comments?.length || 0 }})
                </span>
              </h2>

              <!-- 评论输入框 -->
              <div class="comment-input mb-8">
                <div class="flex items-start gap-4">
                  <el-avatar :size="40" :src="userAvatar" />
                  <div class="flex-1">
                    <el-input
                      v-model="commentContent"
                      type="textarea"
                      :rows="3"
                      placeholder="写下你的评论..."
                      resize="none"
                      maxlength="500"
                      show-word-limit
                    />
                    <div class="flex justify-end mt-4">
                      <el-button type="primary" @click="handleCommentSubmit">
                        发表评论
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 评论列表 -->
              <div class="comments-list space-y-6">
                <div
                  v-for="comment in newsDetail.comments"
                  :key="comment.id"
                  class="comment-item"
                >
                  <div class="flex items-start gap-4">
                    <el-avatar :size="40" :src="comment.user.avatar" />
                    <div class="flex-1">
                      <div class="flex items-center justify-between mb-2">
                        <div class="user-info">
                          <span
                            class="font-medium text-gray-900 dark:text-white"
                          >
                            {{ comment.user.name }}
                          </span>
                          <span
                            class="text-sm text-gray-500 dark:text-gray-400 ml-2"
                          >
                            {{ formatTime(comment.time) }}
                          </span>
                        </div>
                        <el-dropdown trigger="click">
                          <el-icon class="cursor-pointer"><More /></el-icon>
                          <template #dropdown>
                            <el-dropdown-menu>
                              <el-dropdown-item
                                @click="handleReportComment(comment)"
                              >
                                举报
                              </el-dropdown-item>
                            </el-dropdown-menu>
                          </template>
                        </el-dropdown>
                      </div>
                      <div
                        class="comment-content text-gray-700 dark:text-gray-300 break-all whitespace-pre-wrap"
                      >
                        {{ comment.content }}
                      </div>
                      <div class="comment-actions flex items-center gap-4 mt-2">
                        <span
                          class="action-btn text-sm text-gray-500 dark:text-gray-400 cursor-pointer hover:text-primary-600 dark:hover:text-primary-400 transition-colors"
                          @click="handleLikeComment(comment)"
                        >
                          <el-icon class="mr-1">
                            <component
                              :is="
                                comment.isLiked ? 'ThumbsUpFilled' : 'ThumbsUp'
                              "
                            />
                          </el-icon>
                          {{ comment.likes || "点赞" }}
                        </span>
                        <span
                          class="action-btn text-sm text-gray-500 dark:text-gray-400 cursor-pointer hover:text-primary-600 dark:hover:text-primary-400 transition-colors"
                          @click="handleReplyComment(comment)"
                        >
                          <el-icon class="mr-1"><ChatDotRound /></el-icon>
                          回复
                        </span>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 加载更多 -->
                <div
                  v-if="hasMoreComments"
                  class="load-more flex justify-center mt-8"
                >
                  <el-button text @click="loadMoreComments">
                    加载更多评论
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧边栏 -->
        <div class="sidebar lg:w-80 flex-shrink-0">
          <!-- 相关推荐 -->
          <div
            class="related-news bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-6"
          >
            <h3
              class="text-lg font-medium text-gray-900 dark:text-white mb-4 flex items-center"
            >
              <el-icon class="mr-2"><Connection /></el-icon>
              相关推荐
            </h3>
            <div class="related-news-list space-y-4">
              <div
                v-for="news in relatedNews"
                :key="news.id"
                class="related-news-item group cursor-pointer"
                @click="handleNewsClick(news)"
              >
                <div class="relative rounded-lg overflow-hidden mb-2">
                  <el-image
                    :src="news.image"
                    class="w-full h-40 object-cover group-hover:scale-105 transition-transform duration-300"
                  />
                  <div
                    class="absolute inset-0 bg-black/30 group-hover:bg-black/10 transition-colors"
                  ></div>
                </div>
                <h4
                  class="text-sm font-medium text-gray-900 dark:text-white group-hover:text-primary-600 dark:group-hover:text-primary-400 line-clamp-2 mb-2 transition-colors"
                >
                  {{ news.title }}
                </h4>
                <div
                  class="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400"
                >
                  <span>{{ formatTime(news.date) }}</span>
                  <span class="flex items-center">
                    <el-icon class="mr-1"><View /></el-icon>
                    {{ formatNumber(news.views) }}
                  </span>
                </div>
              </div>
            </div>
          </div>

          <!-- 热门标签 -->
          <div
            class="hot-tags bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6"
          >
            <h3
              class="text-lg font-medium text-gray-900 dark:text-white mb-4 flex items-center"
            >
              <el-icon class="mr-2"><Collection /></el-icon>
              热门标签
            </h3>
            <div class="tags-cloud flex flex-wrap gap-2">
              <el-tag
                v-for="tag in hotTags"
                :key="tag.name"
                :type="tag.type"
                effect="light"
                class="cursor-pointer hover:scale-105 transition-transform"
                @click="handleTagClick(tag)"
              >
                {{ tag.name }}
                <span class="ml-1 opacity-75">({{ tag.count }})</span>
              </el-tag>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分享弹窗 -->
    <el-dialog
      v-model="showShareDialog"
      title="分享文章"
      width="360px"
      align-center
    >
      <div class="share-options grid grid-cols-4 gap-4">
        <div
          v-for="platform in sharePlatforms"
          :key="platform.name"
          class="share-item flex flex-col items-center cursor-pointer hover:text-primary-600 transition-colors"
          @click="handleShareTo(platform)"
        >
          <el-icon :size="24" class="mb-2">
            <component :is="platform.icon" />
          </el-icon>
          <span class="text-sm">{{ platform.label }}</span>
        </div>
      </div>
      <div class="mt-6">
        <div class="flex items-center bg-gray-50 dark:bg-gray-700 rounded p-2">
          <input
            type="text"
            :value="generateShareUrl"
            class="flex-1 bg-transparent border-none outline-none text-sm"
            readonly
          />
          <el-button type="primary" link @click="copyShareUrl">
            复制链接
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  Back,
  Calendar,
  View,
  Star,
  Share,
  ThumbsUp,
  ThumbsUpFilled,
  ChatDotRound,
  More,
  Picture,
  Connection,
  Collection,
  CopyDocument,
  Wechat,
  Weibo,
} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import "dayjs/locale/zh-cn";
import {
  newsDetailData,
  relatedNewsData,
  hotTagsData,
  sharePlatformsData,
  categoriesData
} from './detailData';

// 配置dayjs
dayjs.extend(relativeTime);
dayjs.locale("zh-cn");

const router = useRouter();
const route = useRoute();
const loading = ref(false);
const showShareDialog = ref(false);
const commentContent = ref("");
const userAvatar = ref("https://api.dicebear.com/7.x/initials/svg?seed=Guest"); // 当前用户头像，使用在线头像库

// 新闻详情数据
const newsDetail = ref({ ...newsDetailData });

// 相关推荐
const relatedNews = ref(relatedNewsData);

// 热门标签
const hotTags = ref(hotTagsData);

// 分享平台
const sharePlatforms = sharePlatformsData;

// 生成分享链接
const generateShareUrl = computed(() => {
  return `${window.location.origin}/news/${newsDetail.value.id}`;
});

// 是否有更多评论
const hasMoreComments = ref(true);

// 获取新闻详情
const getNewsDetail = async () => {
  loading.value = true;
  try {
    // TODO: 调用获取新闻详情API
    const response = await new Promise((resolve) => {
      setTimeout(() => {
        resolve({ ...newsDetailData });
      }, 500);
    });

    newsDetail.value = response;
  } catch (error) {
    console.error("获取新闻详情失败:", error);
    ElMessage.error("获取新闻详情失败");
    // 使用测试数据作为后备
    newsDetail.value = { ...newsDetailData };
  } finally {
    loading.value = false;
  }
};

// 获取相关推荐
const getRelatedNews = async () => {
  try {
    // TODO: 调用获取相关推荐API
    const response = await new Promise((resolve) => {
      setTimeout(() => {
        resolve([...relatedNewsData]);
      }, 300);
    });

    relatedNews.value = response;
  } catch (error) {
    console.error("获取相关推荐失败:", error);
    // 使用测试数据作为后备
    relatedNews.value = [...relatedNewsData];
  }
};

// 获取热门标签
const getHotTags = async () => {
  try {
    // TODO: 调用获取热门标签API
    const response = await new Promise((resolve) => {
      setTimeout(() => {
        resolve([...hotTagsData]);
      }, 300);
    });

    hotTags.value = response;
  } catch (error) {
    console.error("获取热门标签失败:", error);
    // 使用测试数据作为后备
    hotTags.value = [...hotTagsData];
  }
};

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format("YYYY-MM-DD");
};

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).fromNow();
};

// 格式化数字
const formatNumber = (num) => {
  return new Intl.NumberFormat().format(num);
};

// 获取分类标签类型
const getCategoryType = (category) => {
  const categoryItem = categoriesData.find((item) => item.label === category);
  return categoryItem?.type || "";
};

// 处理点赞
const handleLike = async () => {
  try {
    // TODO: 调用点赞API
    await new Promise((resolve) => setTimeout(resolve, 500));
    newsDetail.value.isLiked = !newsDetail.value.isLiked;
    newsDetail.value.likes += newsDetail.value.isLiked ? 1 : -1;
    ElMessage.success(newsDetail.value.isLiked ? "点赞成功" : "已取消点赞");
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 处理收藏
const handleFavorite = async () => {
  try {
    // TODO: 调用收藏API
    await new Promise((resolve) => setTimeout(resolve, 500));
    newsDetail.value.isFavorited = !newsDetail.value.isFavorited;
    newsDetail.value.favorites += newsDetail.value.isFavorited ? 1 : -1;
    ElMessage.success(newsDetail.value.isFavorited ? "收藏成功" : "已取消收藏");
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 处理分享
const handleShare = () => {
  showShareDialog.value = true;
};

// 处理评论提交
const handleCommentSubmit = async () => {
  if (!commentContent.value.trim()) {
    ElMessage.warning("请输入评论内容");
    return;
  }

  try {
    // TODO: 调用发表评论API
    await new Promise((resolve) => setTimeout(resolve, 500));

    // 模拟添加评论
    const newComment = {
      id: Date.now(),
      content: commentContent.value,
      time: new Date().toISOString(),
      likes: 0,
      isLiked: false,
      user: {
        name: "游客",
        avatar: userAvatar.value,
      },
    };

    newsDetail.value.comments.unshift(newComment);
    commentContent.value = "";
    ElMessage.success("评论发表成功");
  } catch (error) {
    console.error("评论发表失败:", error);
    ElMessage.error("评论发表失败");
  }
};

// 处理评论点赞
const handleLikeComment = async (comment) => {
  try {
    // TODO: 调用评论点赞API
    await new Promise((resolve) => setTimeout(resolve, 500));
    comment.isLiked = !comment.isLiked;
    comment.likes += comment.isLiked ? 1 : -1;
    ElMessage.success(comment.isLiked ? "点赞成功" : "已取消点赞");
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 处理评论回复
const handleReplyComment = (comment) => {
  commentContent.value = `@${comment.user.name} `;
};

// 处理评论举报
const handleReportComment = async (comment) => {
  try {
    await ElMessageBox.confirm("确定要举报这条评论吗？", "举报确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    // TODO: 调用举报API
    await new Promise((resolve) => setTimeout(resolve, 500));
    ElMessage.success("举报已提交，我们会尽快处理");
  } catch {
    // 用户取消操作
  }
};

// 处理新闻点击
const handleNewsClick = (news) => {
  router.push(`/news/${news.id}`);
};

// 处理标签点击
const handleTagClick = (tag) => {
  router.push({
    path: "/news",
    query: { tag: typeof tag === 'object' ? tag.name : tag },
  });
};

// 加载更多评论
const loadMoreComments = async () => {
  try {
    // TODO: 调用加载更多评论API
    await new Promise((resolve) => setTimeout(resolve, 500));
    hasMoreComments.value = false;
  } catch (error) {
    console.error("加载更多评论失败:", error);
    ElMessage.error("加载更多评论失败");
  }
};

// 处理分享到具体平台
const handleShareTo = (platform) => {
  // TODO: 实现具体分享逻辑
  ElMessage.success(`分享到${platform.label}`);
  showShareDialog.value = false;
};

// 复制分享链接
const copyShareUrl = async () => {
  try {
    await navigator.clipboard.writeText(generateShareUrl.value);
    ElMessage.success("链接已复制到剪贴板");
  } catch (err) {
    ElMessage.error("复制失败，请手动复制");
  }
};

// 页面加载时获取数据
onMounted(() => {
  getNewsDetail();
  getRelatedNews();
  getHotTags();
});
</script>

<style lang="scss" scoped>
.news-detail-page {
  @apply min-h-screen bg-gray-50 dark:bg-gray-900;

  .news-body {
    @apply text-gray-700 dark:text-gray-300;

    :deep(h1) {
      @apply text-3xl font-bold text-gray-900 dark:text-white my-6;
    }

    :deep(h2) {
      @apply text-2xl font-bold text-gray-900 dark:text-white my-5;
    }

    :deep(h3) {
      @apply text-xl font-bold text-gray-900 dark:text-white my-4;
    }

    :deep(p) {
      @apply mb-4 leading-relaxed;
    }

    :deep(ul),
    :deep(ol) {
      @apply list-disc list-inside mb-4 space-y-2;
    }

    :deep(img) {
      @apply rounded-lg my-4 mx-auto;
    }

    :deep(blockquote) {
      @apply border-l-4 border-gray-200 dark:border-gray-700 pl-4 my-4 italic;
    }

    :deep(a) {
      @apply text-primary-600 dark:text-primary-400 hover:underline;
    }
  }

  .comment-item {
    @apply border-b border-gray-100 dark:border-gray-700 pb-6;
    &:last-child {
      @apply border-b-0 pb-0;
    }
  }

  .image-placeholder {
    @apply flex items-center justify-center w-full h-full bg-gray-200 dark:bg-gray-700;
    .el-icon {
      @apply text-4xl text-gray-400 dark:text-gray-500;
    }
  }
}
</style>
